#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>


using namespace std;

//注意，这里的mutex不是给代码段进行加锁，而是给条件变量维护的线程队列加锁
//

typedef struct
{
    int res;
    int is_wait;           //判断条件
    pthread_cond_t cond;   //定义条件变量
    pthread_mutex_t mutex; //定义互斥锁
} Result;                  //将结果保存到Result中，然后从Result中获取结果


//计算并讲结果放置到线程运行函数
void* set_fn(void*arg){

    Result*r=(Result*)arg;
    
    int i=1,sum=0;
    for(;i<=100;i++){
        sum+=i;
    }
    //将计算结果放置到res中

    r->res=sum;

    pthread_mutex_lock(&r->mutex);
    //判断获取结果的线程是都等待
    while(!r->is_wait){
        pthread_mutex_unlock(&r->mutex);

        usleep(100);
        pthread_mutex_lock(&r->mutex);
    }
    pthread_mutex_unlock(&r->mutex);

    //唤醒等待的线程
    pthread_cond_broadcast(&r->cond);



    

    return (void*)0;
}


void* get_fn(void*arg){


    Result*r=(Result*)arg;

    //对共享的判断条件进行加锁
    pthread_mutex_lock(&r->mutex);
    r->is_wait=1;//设置成1表示该线程条件已经满足，可以开始执行了
    pthread_cond_wait(&r->cond,&r->mutex);
    pthread_mutex_unlock(&r->mutex);

    int res=r->res;
    std::cout<<"result:"<<res<<std::endl;
    
    return (void*)0;

}



int main(){

    int err;
    pthread_t cal,get;

    Result r;
    r.is_wait=0;
    pthread_mutex_init(&r.mutex,NULL);
    pthread_cond_init(&r.cond,NULL);

    
    if ((err = pthread_create(&cal, NULL, set_fn, (void*)&r)) != 0)
    {

        perror("pthread_create error");
        exit(1);
    }

    if ((err = pthread_create(&get, NULL, get_fn, (void*)&r)) != 0)
    {
        perror("pthread_create");
        exit(1);
    }

  

    pthread_join(cal, NULL);
    pthread_join(get, NULL);
    
    pthread_cond_destroy(&r.cond);
    pthread_mutex_destroy(&r.mutex);

    return 0;
}